package com.xjzd.pattern.strategy.pay;

import java.math.BigDecimal;
import java.util.Arrays;

/**
 * 枚举是功能完整的类，它可以：
 * <p>拥有字段
 * <p>定义构造函数
 * <p>实现方法
 * <p>持有行为（函数式接口）
 */
public enum PayChannel {

    WECHAT("wechat", amount -> System.out.println("使用微信支付 " + amount)),
    ALIPAY("alipay", amount -> System.out.println("使用支付宝支付 " + amount)),
    BANKCARD("bankcard", amount -> System.out.println("使用银行卡支付 " + amount)),
    PAYPAL("paypal", amount -> System.out.println("使用PayPal支付 " + amount)),
    APPLEPAY("applepay", amount -> System.out.println("使用ApplePay支付 " + amount));;

    private final String code;

    private final PayHandler handler;

    PayChannel(String code, PayHandler handler) {
        this.code = code;
        this.handler = handler;
    }

    public void pay(BigDecimal amount) {
        handler.pay(amount);
    }

    public String getCode() {
        return code;
    }

    public static PayChannel fromCode(String code) {
        return Arrays.stream(values())
                .filter(channel -> channel.code.equals(code))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("Unknown payment method code: " + code));
    }

    public static void main(String[] args) {
        String channelCode = "alipay";
        BigDecimal amount = new BigDecimal("100.00");
        PayChannel channel = PayChannel.fromCode(channelCode);
        channel.pay(amount);

        PayChannel.WECHAT.pay(amount);
    }
}
